<template>
  <div class="question-import">
    <!-- 导入说明 -->
    <el-card class="info-card">
      <template #header>
        <div class="card-header">
          <el-icon><InfoFilled /></el-icon>
          <span>导入说明</span>
        </div>
      </template>
      <div class="import-info">
        <el-steps :active="currentStep" finish-status="success">
          <el-step title="下载模板" description="下载Excel导入模板" />
          <el-step title="填写数据" description="按模板格式填写试题数据" />
          <el-step title="上传文件" description="上传填写好的Excel文件" />
          <el-step title="导入完成" description="系统处理并导入试题" />
        </el-steps>
      </div>
    </el-card>

    <!-- 模板下载 -->
    <el-card class="template-card">
      <template #header>
        <span>模板下载</span>
      </template>
      <div class="template-content">
        <div class="template-info">
          <el-icon><Document /></el-icon>
          <div>
            <h4>试题导入模板.xlsx</h4>
            <p>包含试题标题、内容、类型、难度、分值、选项等字段</p>
          </div>
        </div>
        <el-button type="primary" @click="downloadTemplate" :loading="downloadLoading">
          <el-icon><Download /></el-icon>
          下载模板
        </el-button>
      </div>
    </el-card>

    <!-- 文件上传 -->
    <el-card class="upload-card">
      <template #header>
        <span>文件上传</span>
      </template>
      <div class="upload-content">
        <el-upload
          ref="uploadRef"
          class="upload-demo"
          drag
          :action="uploadAction"
          :headers="uploadHeaders"
          :before-upload="beforeUpload"
          :on-success="handleUploadSuccess"
          :on-error="handleUploadError"
          :on-progress="handleUploadProgress"
          :file-list="fileList"
          :limit="1"
          accept=".xlsx,.xls"
        >
          <el-icon class="el-icon--upload"><upload-filled /></el-icon>
          <div class="el-upload__text">
            将Excel文件拖到此处，或<em>点击上传</em>
          </div>
          <template #tip>
            <div class="el-upload__tip">
              只能上传 .xlsx/.xls 文件，且不超过 10MB
            </div>
          </template>
        </el-upload>

        <!-- 上传进度 -->
        <div v-if="uploading" class="upload-progress">
          <el-progress :percentage="uploadProgress" :status="uploadStatus" />
          <p>{{ uploadStatusText }}</p>
        </div>
      </div>
    </el-card>

    <!-- 导入历史 -->
    <el-card class="history-card">
      <template #header>
        <div class="card-header">
          <span>导入历史</span>
          <el-button @click="fetchImportHistory" icon="Refresh">刷新</el-button>
        </div>
      </template>
      <el-table :data="importHistory" v-loading="historyLoading" empty-text="暂无导入记录">
        <el-table-column prop="fileName" label="文件名" min-width="160" show-overflow-tooltip />
        <el-table-column prop="totalCount" label="总数量" width="140" align="center" />
        <el-table-column prop="successCount" label="成功数量" width="140" align="center">
          <template #default="scope">
            <el-tag type="success">{{ scope.row.successCount }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="failCount" label="失败数量" width="140" align="center">
          <template #default="scope">
            <el-tag v-if="scope.row.failCount > 0" type="danger">{{ scope.row.failCount }}</el-tag>
            <span v-else>0</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="140" align="center">
          <template #default="scope">
            <el-tag :type="getStatusTagType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="导入时间" width="180" align="center">
          <template #default="scope">
            {{ formatDate(scope.row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" align="center">
          <template #default="scope">
            <el-button 
              v-if="scope.row.errorFile"
              size="small" 
              type="warning" 
              @click="downloadErrorFile(scope.row)"
            >
              下载错误报告
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="historyPagination.page"
          v-model:page-size="historyPagination.size"
          :page-sizes="[10, 20, 50]"
          :total="historyPagination.total"
          layout="total, sizes, prev, pager, next"
          @size-change="handleHistorySizeChange"
          @current-change="handleHistoryCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { importApi } from '@/api/import'

// 响应式数据
const currentStep = ref(0)
const downloadLoading = ref(false)
const uploading = ref(false)
const uploadProgress = ref(0)
const uploadStatus = ref<'success' | 'exception' | undefined>()
const uploadStatusText = ref('')
const fileList = ref<any[]>([])
const uploadRef = ref()

const historyLoading = ref(false)
const importHistory = ref<any[]>([])
const historyPagination = ref({
  page: 1,
  size: 10,
  total: 0
})

// 上传配置
const uploadAction = computed(() => `${import.meta.env.VITE_API_BASE_URL}/questions/import`)
const uploadHeaders = computed(() => ({
  'Authorization': `Bearer ${localStorage.getItem('token')}`
}))

// 下载模板
const downloadTemplate = async () => {
  downloadLoading.value = true
  try {
    const response = await importApi.downloadTemplate()
    const blob = new Blob([response.data])
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = '试题导入模板.xlsx'
    link.click()
    window.URL.revokeObjectURL(url)
    ElMessage.success('模板下载成功')
    currentStep.value = 1
  } catch (error) {
    console.error('下载模板失败:', error)
    ElMessage.error('下载模板失败')
  } finally {
    downloadLoading.value = false
  }
}

// 上传前检查
const beforeUpload = (file: File) => {
  const isExcel = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' || 
                  file.type === 'application/vnd.ms-excel'
  const isLt10M = file.size / 1024 / 1024 < 10

  if (!isExcel) {
    ElMessage.error('只能上传 Excel 文件!')
    return false
  }
  if (!isLt10M) {
    ElMessage.error('文件大小不能超过 10MB!')
    return false
  }

  uploading.value = true
  uploadProgress.value = 0
  uploadStatus.value = undefined
  uploadStatusText.value = '正在上传...'
  currentStep.value = 2
  return true
}

// 上传进度
const handleUploadProgress = (event: any) => {
  uploadProgress.value = Math.round(event.percent)
}

// 上传成功
const handleUploadSuccess = (response: any) => {
  uploading.value = false
  uploadStatus.value = 'success'
  uploadStatusText.value = '上传成功，正在处理...'
  
  if (response.success) {
    ElMessage.success(`导入成功！成功导入 ${response.data.successCount} 条试题`)
    currentStep.value = 3
    fetchImportHistory()
    fileList.value = []
  } else {
    ElMessage.error(response.message || '导入失败')
    uploadStatus.value = 'exception'
    uploadStatusText.value = response.message || '导入失败'
  }
}

// 上传失败
const handleUploadError = (error: any) => {
  uploading.value = false
  uploadStatus.value = 'exception'
  uploadStatusText.value = '上传失败'
  ElMessage.error('上传失败，请重试')
  console.error('上传失败:', error)
}

// 获取导入历史
const fetchImportHistory = async () => {
  historyLoading.value = true
  try {
    const response = await importApi.getImportHistory({
      page: historyPagination.value.page - 1,
      size: historyPagination.value.size,
      type: 'QUESTION'
    })
    importHistory.value = response.data.content || []
    historyPagination.value.total = response.data.totalElements || 0
  } catch (error) {
    console.error('获取导入历史失败:', error)
    ElMessage.error('获取导入历史失败')
  } finally {
    historyLoading.value = false
  }
}

// 历史记录分页
const handleHistorySizeChange = () => {
  historyPagination.value.page = 1
  fetchImportHistory()
}

const handleHistoryCurrentChange = () => {
  fetchImportHistory()
}

// 下载错误报告
const downloadErrorFile = async (record: any) => {
  try {
    const response = await importApi.downloadErrorFile(record.id)
    const blob = new Blob([response.data])
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = `导入错误报告_${record.fileName}.xlsx`
    link.click()
    window.URL.revokeObjectURL(url)
    ElMessage.success('错误报告下载成功')
  } catch (error) {
    console.error('下载错误报告失败:', error)
    ElMessage.error('下载错误报告失败')
  }
}

// 获取状态标签类型
const getStatusTagType = (status: string) => {
  const typeMap: Record<string, string> = {
    'SUCCESS': 'success',
    'FAILED': 'danger',
    'PARTIAL': 'warning',
    'PROCESSING': 'info'
  }
  return typeMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status: string) => {
  const textMap: Record<string, string> = {
    'SUCCESS': '成功',
    'FAILED': '失败',
    'PARTIAL': '部分成功',
    'PROCESSING': '处理中'
  }
  return textMap[status] || status
}

// 格式化日期
const formatDate = (dateString: string) => {
  if (!dateString) return '-'
  return new Date(dateString).toLocaleString('zh-CN')
}

// 组件挂载
onMounted(() => {
  fetchImportHistory()
})
</script>

<style scoped>
.question-import {
  padding: 20px;
}

.info-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  align-items: center;
  gap: 8px;
}

.import-info {
  padding: 20px 0;
}

.template-card {
  margin-bottom: 20px;
}

.template-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 0;
}

.template-info {
  display: flex;
  align-items: center;
  gap: 16px;
}

.template-info .el-icon {
  font-size: 48px;
  color: #409eff;
}

.template-info h4 {
  margin: 0 0 8px 0;
  color: #303133;
}

.template-info p {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.upload-card {
  margin-bottom: 20px;
}

.upload-content {
  padding: 20px 0;
}

.upload-progress {
  margin-top: 20px;
  text-align: center;
}

.upload-progress p {
  margin-top: 10px;
  color: #606266;
}

.history-card {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

:deep(.el-upload-dragger) {
  border-radius: 8px;
}

:deep(.el-steps) {
  margin: 20px 0;
}

:deep(.el-table) {
  border-radius: 8px;
}

:deep(.el-table th) {
  background-color: #fafafa;
  color: #606266;
  font-weight: 600;
}
</style>